<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>阿里云盘编辑</title>
    <script src="asserts/js/init.js?from=antd&plugins=aliyundrive,md5"></script>
    <script>
        if(utils.getParamer("sdk")){
            document.write("<script src='"+utils.getParamer("sdk")+"'></s"+"cript>");
        }
    </script>
    <style>
        iframe{
            width: 100%;
            height: calc(100vh - 40px);
            border: none;
        }
        .text-color{
            color:#3d4757;
            line-height: 32px;
        }
        .ant-tooltip-inner{
            background-color:#ffffff;
            color: #3d4757;
        }
        .ant-tooltip-arrow::before{
            background-color:#ffffff;
        }
    </style>
</head>
<div id="app">
    <a-row>
        <a-col :span="5">
            <a-button-group>
                <a-tooltip placement="bottom">
                    <template slot="title">
                        <span>查看</span>
                    </template>
                    <a-button v-if="mode=='edit' && iframe.file_id" type="link" icon="eye" @click="fileView()"></a-button>
                </a-tooltip>
                <a-tooltip placement="bottom">
                    <template slot="title">
                        <span>编辑</span>
                    </template>
                    <a-button v-if="mode=='read' && iframe.file_id && pluginsConfig.canEdit" type="link" icon="edit" @click="fileEdit()"></a-button>
                </a-tooltip>
                <a-tooltip placement="bottom">
                    <template slot="title">
                        <span>保存</span>
                    </template>
                    <a-button v-if="mode=='edit' && iframe.file_id && pluginsConfig.canEdit" type="link" icon="save" @click="fileSave()"></a-button>
                </a-tooltip>
            </a-button-group>
        </a-col>
        <a-col :span="11">
            <template v-if="mode == 'edit' && pluginsConfig.canShow">
                <span v-if="autoSave.text" class="text-color">当前已开启自动保存({{autoSave.text}})</span>
                <span v-if="!autoSave.text" class="text-color">请使用左侧保存按钮保存到可道云,否则文件将不会被保存</span>
            </template>
        </a-col>
        <a-col :span="6">
            <a-tooltip placement="bottom" v-for="(item,i) in docConfig.persons">
                <template v-if="i < 3">
                    <template slot="title">
                        <span>{{item.name}}</span>
                    </template>
                    <a-avatar :src="item.url"></a-avatar>
                </template>
            </a-tooltip>
            <a-popover placement="bottom" v-if="docConfig.persons.length > 3">
                <template slot="content">
                    <p v-for="item in docConfig.persons">
                        <a-avatar :src="item.url"></a-avatar>
                        <span>{{item.name}}</span>
                    </p>
                </template>
                <template slot="title">
                    <span>{{docConfig.persons.length}}人正在观看</span>
                </template>
                <a-badge :count="docConfig.persons.length-3"></a-badge>
            </a-popover>
        </a-col>
        <a-col :span="2">
            <a-tooltip placement="bottom">
                <template slot="title">
                    <span>分享地址</span>
                </template>
                <a-button type="link" icon="share-alt" @click="toSetDocConfig()"></a-button>
            </a-tooltip>
        </a-col>
    </a-row>
    <a-row>
        <a-col :span="24">
            <iframe ref="iframe" :src="iframe.src"></iframe>
        </a-col>
    </a-row>
    <a-modal v-model="docConfig.showSet" title="文档分享" @ok="shareDoc()" ok-text="复制分享链接" cancel-text="取消" :mask-closable="false">
        <a-row>
            <a-col :span="24" style="color:red;text-align: center;">协同方不具备将数据写到可道云</a-col>
            <a-col :span="24" style="color:red;text-align: center;">请通知协同方修改后提醒创建方进入保存</a-col>
        </a-row>
        <a-form-model layout="horizontal" :model="docConfig.docSet" :label-col="{ span: 6 }" :wrapper-col="{ span: 12 }">
            <a-form-model-item label="需要登录" prop="needLogin">
                <a-switch v-model="docConfig.docSet.needLogin"></a-switch>
            </a-form-model-item>
            <a-form-model-item label="需要密码" prop="needPass">
                <a-switch v-model="docConfig.docSet.needPass"></a-switch>
            </a-form-model-item>
            <a-form-model-item v-if="docConfig.docSet.needPass" label="文档密码" prop="password">
                <a-input-password v-model="docConfig.docSet.password" placeholder="请输入文档密码"></a-input-password>
            </a-form-model-item>
        </a-form-model>
    </a-modal>
</div>
</body>
<script>
    window.addEventListener("message",function (res){
        if(window.vm){
            window.vm.sendAlitoken(res);
        }
    });
    Vue.app({
        data:{
            iframe:{
                src:'',
                file_id:'',
                access_token:'',
                refresh_token:'',
                save_status:0,//0:未保存或保存成功或失败,请求保存,1:收到保存,2:保存中
            },
            file:{
                url:'',
                name:''
            },
            mode:"read",
            autoSave:{
                init:false,
                text:null,
                value:0,
                defValue:10
            },
            pluginsConfig:{
            },
            docConfig:{
                persons:[],
                password:"",
                showSet:false,
                docSet:{
                    needPass:false,
                    needLogin:false,
                    password:""
                }
            },
            pageUrl:""
        },
        methods: {
            getParentHost:function (){
                var that = this;
                if(that.file.host){
                    return that.file.host;
                }
                var path = utils.rootPath;
                var pathsz = path.split("/");
                pathsz.length = pathsz.length -2;
                path = pathsz.join("/");
                that.file.host = path;
                return that.file.host;
            },
            sendAlitoken:function (res){
                var that = this;
                var data = JSON.parse(res.data);
                if(data.eventName == "ready"){
                    var setToken = {"eventName":"setToken","data":{"token":that.iframe.access_token,"timeout":100000,"hasRefreshTokenConfig":true}};
                    that.$refs["iframe"].contentWindow.postMessage(JSON.stringify(setToken), '*');
                    var setConfig = {"eventName":"setConfig","data":{"refreshToken":{"eventName":"api.getToken"},"version":"1.1.5"}};
                    that.$refs["iframe"].contentWindow.postMessage(JSON.stringify(setConfig), '*');
                }else if(data.eventName == "wps.api.reply"){
                    console.log(data.data.result);
                    if(data.data.result == "nochange" || data.data.result == "ok"){
                        if(that.iframe.save_status == 0){
                            that.iframe.save_status = 1;
                            that.fileSave();
                        }
                    }else if(data.data.error){
                        if(data.data.error == "PermissionDenied"){
                            that.fileView();
                        }else if(data.data.reason == "SavedEmptyFile"){
                            utils.$.errorMsg("空文件不允许保存");
                        }else{
                            console.log(res);
                        }
                    }else{
                        console.log(res);
                    }
                }else{
                    console.log(res);
                }
            },
            fileView:function (){
                var that = this;
                that.getAliFileId(function (){
                    that.aliyunView(function (){
                        that.mode = "read";
                        document.title = "[只读]"+that.file.name;
                    });
                });
            },
            fileEdit:function (){
                var that = this;
                that.getAliFileId(function (){
                    that.aliyunEdit(function (){
                        that.mode = "edit";
                        document.title = "[编辑]"+that.file.name;
                        if(that.pluginsConfig.save){
                            that.autoSaveAction();
                        }
                    });
                });
            },
            fileSave:function(){
                var that = this;
                if(that.iframe.save_status == 0){
                    that.$refs["iframe"].contentWindow.postMessage(JSON.stringify({"data":{"api":"save"},"msgId":2,"eventName":"wps.jssdk.api"}), '*');
                }else if(that.iframe.save_status == 1){
                    that.iframe.save_status = 2;
                    utils.$.attr.tmpMask = false;
                    if(that.autoSave.init){
                        that.autoSave.text = "正在保存中...请稍后";
                        if(!that.pluginsConfig.canShow){
                            utils.$.successMsg("正在保存中...请稍后");
                        }
                    }else{
                        utils.$.loading("正在保存中...请稍后");
                    }

                    aliyundrive.saveFile(that.iframe.file_id,function (res){
                        utils.$.cancelLoading();
                        that.iframe.save_status = 0;
                        if(that.autoSave.init){
                            that.autoSave.text = res.msg;
                            that.autoSave.value = that.autoSave.defValue;
                            if(!that.pluginsConfig.canShow){
                                if(res.flag){
                                    utils.$.successMsg(res.msg);
                                }else{
                                    utils.$.errorMsg(res.msg);
                                }
                            }
                        }else{
                            if(res.flag){
                                utils.$.successMsg(res.msg);
                            }else{
                                utils.$.errorMsg(res.msg);
                            }
                        }
                    });
                }else if(that.iframe.save_status == 2){
                    //utils.$.errorMsg("正在保存中，请稍后");
                }
            },
            getAliFileId:function (fn){
                var that = this;
                if(that.iframe.file_id){
                    fn();
                    return;
                }
                if(utils.getParamer("file_id")){
                    that.file.file_id = utils.getParamer("file_id");
                }
                aliyundrive.getFileId(that.file,function (fid){
                    that.iframe.file_id = fid;
                    that.pageUrl = utils.urlAddProp(window.location.href,"file_id",that.iframe.file_id);
                    aliyundrive.getShortUrl(that.pageUrl,function (url){
                        that.pageUrl = url;
                    });
                    fn();
                });
            },
            aliyunEdit:function (fn){
                var that = this;
                aliyundrive.getEditDataByFid(that.iframe.file_id,function (res){
                    if(res.flag){
                        that.iframe.access_token = res.data.office_access_token;
                        that.iframe.refresh_token = res.data.office_refresh_token;
                        that.iframe.src = res.data.edit_url;
                        utils.$.cancelLoading();
                        fn();
                    }else{
                        utils.$.errorMsg("当前文档不可编辑");
                        that.aliyunView(function (){
                            that.mode = "read";
                            document.title = "[只读]"+that.file.name;
                        });
                    }
                });
            },
            aliyunView:function (fn){
                var that = this;
                aliyundrive.getPreviewDataByFid(that.iframe.file_id,function (res){
                        if(res.flag){
                            that.iframe.access_token = res.data.access_token;
                            that.iframe.refresh_token = "";
                            that.iframe.src = res.data.preview_url;
                            utils.$.cancelLoading();
                            fn();
                        }else{
                            utils.$.errorMsg(res.msg?res.msg:"当前文档不可预览");
                        }
                });
            },
            autoSaveAction:function (){
                var that = this;
                if(that.autoSave.init){
                    return;
                }
                var sv = that.pluginsConfig.sv;
                if(sv && !isNaN(sv)){
                    that.autoSave.defValue = sv*1;
                }
                that.autoSave.value = that.autoSave.defValue;
                that.autoSave.text = "保存倒计时"+that.autoSave.value;
                that.autoSave.init = true;
                setInterval(function (){
                    if(that.mode != 'edit'){
                        return;
                    }
                    if(that.iframe.save_status == 2){
                        return;
                    }
                    that.autoSave.value--;
                    if(that.autoSave.value <= 0){
                        that.fileSave();
                    }else{
                        that.autoSave.text = "保存倒计时"+that.autoSave.value;
                    }
                },1000);
            },
            initData:function (){
                var that = this;
                var url = utils.getParamer("url");
                var name = utils.getParamer("name");
                that.file.url = url;
                that.file.name = name;
                if(that.pluginsConfig.canEdit){
                    that.fileEdit();
                }else{
                    that.fileView();
                }
            },
            initConfig:function (fn){
                var that = this;
                aliyundrive.getConfig(function (config){
                    that.pluginsConfig = config;
                    fn();
                });
                that.getPersons();
            },
            toSetDocConfig:function (){
                var that = this;
                aliyundrive.hasSetDocConfigAuth(function (flag){
                    if(flag){
                        that.docConfig.showSet = true;
                    }else{
                        that.copyUrl();
                    }
                });
            },
            shareDoc:function (){
                var that = this;
                aliyundrive.setDocConfig(that.docConfig.docSet,function (res){
                    if(!res.flag){
                        utils.$.errorMsg(res.msg);
                        return;
                    }
                    that.docConfig.showSet = false;
                    that.copyUrl();
                });
            },
            copyUrl:function (){
                var that = this;
                if(utils.copyText(that.pageUrl)){
                    utils.$.successMsg("复制成功,请粘贴给别人协同修改");
                }else{
                    prompt("当前浏览器不支持复制,请手动复制",that.pageUrl);
                }
            },
            getPersons:function (){
                var that = this;
                if(that.personAction){
                    return;
                }
                that.personAction = true;
                aliyundrive.getPersons(function (res){
                    var sz = [];
                    if(res.flag){
                        sz = res.data;
                    }
                    that.docConfig.persons = sz;
                    setTimeout(function (){
                        that.personAction = false;
                        that.getPersons();
                    },5000);
                });
            },
            initAuth:function (){
                var that = this;
                if(!that.docConfig.password && utils.getLocalStorage("docPassword")){
                    that.docConfig.password = utils.getLocalStorage("docPassword");
                }
                aliyundrive.getDocConfig(that.docConfig.password,function (res){
                    if(!res.flag){
                        utils.$.errorMsg(res.msg);
                        return;
                    }
                    var config = res.data;
                    if(config.needLogin && !config.checkLogin){
                        aliyundrive.toLogin();
                        return;
                    }
                    if(config.needPass && !config.checkPass){
                        //需要输入密码
                        utils.$.prompt("请输入当前的文档密码",function (flag,text){
                            if(flag){
                               that.docConfig.password=text;
                               that.initAuth();
                            }
                        });
                        return;
                    }
                    utils.setLocalStorage("docPassword",that.docConfig.password);
                    that.initConfig(that.initData);
                });
            }
        },
        mounted:function(){
            var that = this;
            utils.$.loading("正在加载中...请稍后");
            that.initAuth();
            aliyundrive.hasSetDocConfigAuth(function (flag){
                if(!flag){
                    setTimeout(function (){
                        utils.$.alert("协同方不支持将数据写入到可道云,请修改后及时通知创建人进行保存");
                    },3000);
                }
            });
        }
    });
</script>
</html>